package cn.highedu.coolsharkhub.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 演示过滤器
 * urlPatterns = "/*" 表示拦截所有请求
 * filterName = "myFilter" 表示过滤器名称
 * @author HighEDU
 */
@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(MyFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("过滤器初始化");
    }

    /**
     * 过滤器执行方法
     * @param filterChain 过滤器链
     */
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        String requestURI = ((HttpServletRequest) servletRequest).getRequestURI();
        logger.info("过滤器前置处理");
        //执行过滤器链中的下一个过滤器
        logger.info("过滤器执行请求资源: {}", requestURI);
        filterChain.doFilter(servletRequest, servletResponse);
        logger.info("过滤器后置处理");
    }

    @Override
    public void destroy() {
        logger.info("过滤器销毁");
    }
}
